package tl;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author fei
 * @date 2023/1/25 10:59
 * @description ThreadLocal 基本使用
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        House house = new House();
        for (int i = 1; i <= 5; i++){
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                for (int j = 0; j <= size; j++) {
                    house.saleHouse();
                    house.saleVolumeByThreadLocal();
                }
                System.out.println(Thread.currentThread().getName() + "\t" + "号销售卖出：" + house.saleVolume.get());
            }, String.valueOf(i)).start();
        }

        try{ TimeUnit.MILLISECONDS.sleep(300);} catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println(Thread.currentThread().getName() + "\t" + "共计卖出多少套：" + house.saleCount);
    }

}

class House{

    int saleCount = 0;

    public synchronized void saleHouse(){
        ++saleCount;
    }

    // 和下面是等价的，建议不使用这种
    /*ThreadLocal<Integer> saleVolume = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/

    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);

    public void saleVolumeByThreadLocal(){
        saleVolume.set(1 + saleVolume.get());
    }

}
